import React, { useState, useRef, useEffect, useCallback } from "react";
import { Button, message, List } from "antd";
import Modal from "@/components/Modal";
import CommonDisplayPanel from "@/components/CommonDisplayPanel";
import Icon, { Icons } from "@/utils/icons";

import TeamMemberSelector, {
  TeamMemberSelectorRef,
} from "@/components/TeamMemberSelector/index";
import { CloseOutlined } from "@ant-design/icons";
import teamService from "@/services/teamService";
import { User } from "@/types/user";
import UserAvatarWithName from "@/components/UserAvatarWithName";
import AvatarGroup from "@/components/AvatarGroup";

const SpaceTeamMember: React.FC<{
  spaceId: number;
  onDeleteSuccess?: (deletedMember: User) => void;
}> = ({ spaceId, onDeleteSuccess }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 选中的成员 列表
  const [selectedItems, setSelectedItems] = useState<User[]>([]);

  // 已添加的成员列表
  const [existingSelectedItems, setExistingSelectedItems] = useState<User[]>(
    []
  );
  const [messageApi, contextHolder] = message.useMessage();
  const teamMemberSelectorRef = useRef<TeamMemberSelectorRef>(null);

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [memberToDelete, setMemberToDelete] = useState<User | null>(null);

  const [isAdding, setIsAdding] = useState(false); // 添加状态

  const [isErrorModalOpen, setIsErrorModalOpen] = useState(false);
  const [errorMessage, setErrorMessage] = useState<{
    title: string;
    description: string;
  }>({
    title: "",
    description: "",
  });

  const showErrorModal = (title: string, description: string) => {
    setErrorMessage({ title, description });
    setIsErrorModalOpen(true);
  };

  const closeErrorModal = () => {
    setIsErrorModalOpen(false);
  };

  const setSelectedMembersFromAPI = useCallback(async (spaceId: number) => {
    // 模拟从 API 获取已选中的成员
    const members = (await teamService.getAddedMembers(spaceId)) as User[];
    console.log("已从 API 获取已选中的成员:", spaceId);

    setExistingSelectedItems(members);
  }, []);

  useEffect(() => {
    if (spaceId) {
      console.log("Space ID:", spaceId);
      setSelectedMembersFromAPI(spaceId);
    }
  }, [spaceId, setSelectedMembersFromAPI]);

  const handleOpenModal = () => setIsModalOpen(true);
  const handleCloseModal = () => setIsModalOpen(false);

  const handleConfirm = (selected: User[]) => {
    setSelectedItems(selected);
  };

  const handleAdd = () => {
    if (selectedItems.length === 0) {
      messageApi.warning("请先选择成员");
    } else {
      setIsAdding(true); // 设置为添加中
      const userIdList = selectedItems.map((item) => item.id);
      teamService
        .addSpaceMembers({ userIdList, spaceId })
        .then(() => {
          messageApi.info(`添加了 ${selectedItems.length} 个成员`);
          setExistingSelectedItems((prev) => [...prev, ...selectedItems]);
          handleClear();
        })
        .catch(() => {
          messageApi.error("添加成员失败");
        })
        .finally(() => {
          setIsAdding(false); // 添加完成后恢复状态
        });
    }
  };

  const handleRemoveMember = (member: User) => {
    setMemberToDelete(member);
    setIsDeleteModalOpen(true);
  };

  const confirmDeleteMember = () => {
    if (memberToDelete) {
      setExistingSelectedItems((prev) =>
        prev.filter((member) => member.id !== memberToDelete.id)
      );
      setIsDeleteModalOpen(false);
      teamService
        .deleteSpaceMember({
          id: memberToDelete.id,
          spaceId,
        })
        .then(() => {
          messageApi.info("已移除成员");
          onDeleteSuccess?.(memberToDelete); // 调用外部回调
          setMemberToDelete(null);
        })
        .catch(() => {
          showErrorModal(
            "团队人数已达上限30人",
            "无法再添加成员，请重新选择。"
          );
        });
    }
  };

  const cancelDeleteMember = () => {
    setMemberToDelete(null);
    setIsDeleteModalOpen(false);
  };

  const handleClear = () => {
    // 清空 TeamMemberSelector 中的选中值
    teamMemberSelectorRef.current?.clearSelectedItems();
    setSelectedItems([]);
  };

  // 标题 团队成员 + 已添加的成员数量
  const title = (
    <div>
      团队成员
      <span
        style={{ marginLeft: 8, fontSize: 14, color: "rgba(18, 18, 18, 0.5)" }}
      >
        {existingSelectedItems.length > 0
          ? `${existingSelectedItems.length}`
          : ""}
      </span>
    </div>
  );

  return (
    <div>
      <AvatarGroup
        users={existingSelectedItems}
        maxCount={8}
        gap={-5}
        onMoreClick={handleOpenModal}
        showBorder={false}
        alwaysShowDots={true}
      />

      <Modal
        title={title}
        visible={isModalOpen}
        onCancel={handleCloseModal}
        footer={null}
        width={800}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignContent: "center",
            width: "100%",
            gap: 12,
            marginTop: 20,
          }}
        >
          {contextHolder}
          <TeamMemberSelector
            ref={teamMemberSelectorRef}
            onChange={handleConfirm}
            existingSelectedItems={existingSelectedItems} // 传递已添加的成员
          />

          <Button
            type="primary"
            onClick={handleAdd}
            disabled={selectedItems.length === 0 || isAdding} // 禁用条件增加 isAdding
            style={{ gap: 5, height: 38 }}
          >
            <Icons.Plus width={24} fill="#fff" /> 添加
          </Button>
        </div>
        <div
          style={{
            marginTop: 8,
            maxHeight: 470,
            overflowY: "auto",
            padding: 8,
            paddingRight: 0,
            minHeight: 260,
          }}
        >
          <List
            dataSource={existingSelectedItems}
            locale={{
              emptyText: (
                <div
                  style={{
                    textAlign: "center",
                    marginTop: 40,
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                  }}
                >
                  <Icon name="NoResult" size={90} />
                  <p
                    style={{
                      marginTop: 16,
                    }}
                  >
                    未找到结果
                  </p>
                </div>
              ),
            }}
            renderItem={(member) => (
              <List.Item
                className="hover-effect"
                style={{
                  border: "none",
                  padding: "6px 0",
                  display: "flex",
                  justifyContent: "space-between",
                  position: "relative", // 添加相对定位
                }}
              >
                <UserAvatarWithName
                  key={member.id}
                  name={member.name}
                  avatar={member.avatar}
                  size="default"
                  shape="circle"
                />
                {existingSelectedItems.length > 1 && (
                  <Button
                    key={`delete-${member.id}`}
                    type="text"
                    danger
                    icon={<CloseOutlined />}
                    onClick={() => handleRemoveMember(member)}
                    style={{
                      position: "absolute", // 绝对定位
                      right: 0,
                      opacity: 0, // 初始隐藏
                      transition: "opacity 0.2s", // 添加过渡效果
                    }}
                    className="delete-button"
                  />
                )}
              </List.Item>
            )}
          />
        </div>
      </Modal>
      <Modal
        visible={isDeleteModalOpen}
        onOk={confirmDeleteMember}
        onCancel={cancelDeleteMember}
        backgroundColor="#fff"
        okButtonProps={{
          danger: true,
        }}
      >
        <CommonDisplayPanel
          svgIcon="DeleteUserConfirm"
          title={`确认移除成员 ${memberToDelete?.name} 吗？`}
          description="移除后该成员将无法再访问空间，该成员产生的数据不受影响。"
        />
      </Modal>
      <Modal
        visible={isErrorModalOpen}
        onOk={closeErrorModal}
        onCancel={closeErrorModal}
        backgroundColor="#fff"
        okText="知道了"
      >
        <CommonDisplayPanel
          svgIcon="UserLimitReached"
          title={errorMessage.title}
          description={errorMessage.description}
        />
      </Modal>
    </div>
  );
};

export default SpaceTeamMember;
